import React, { forwardRef, useState, useImperativeHandle, useRef } from "react";
import { Form, Input, Select, Space, Button, Table, Tag, Tooltip, Modal, message, Radio, Spin } from '@bytedance/mona-ui';
import { getListFlashWithTimeLimit, setFlashStatus, getDetailFlashAndGoods } from "@Api/productApi"
import CopyAct from './copyActBoxCoentent'
import AutoSetActBox from './autoSetActBox'
import { createTaskId } from "../../../jinritemaiCopyGoods/copyDataFomate"
import { store, useAppSelector } from "~store"
import moment from 'moment'

const { Option } = Select;
function SetLtaLp(props, ref) {
    // const [getListLodin, setLodinDataStatus] = useState(false)

    const dataInfo = {
        product_id: "", // 商品ID
        title: "", // 活动名称
        campaign_status: "", // 活动状态 '':全部 1：未开始，2：进行中， 6：处理中，4：已结束，3已失效
        shop_stype: "", // 优惠类型 1：一口价， 2：直降价 ，3：打折
        page: 1,
        pageSize: 20,
        business_code: ''
    }
    const [getListFlashWithTimeLimitData, setGetListFlashWithTimeLimitData] = useState(dataInfo)
    const [getDataList, setGetDataList] = useState([])
    const [getListLodin, setGetListLodin] = useState(false)
    const [total, setTotals] = useState(0)
    const [selectActType, setSelectActType] = useState('0')
    const [selectGoodsKeys, setSelectGoodsKeys] = useState([])
    const [selectkeysDelet, setSelectkeysDelet] = useState([])
    const [showCopyActModal, setShowCopyActModal] = useState(false)
    const [copyActItemOne, setCopyActItemOne] = useState({})
    const [getDataLodin, setGetDataLodin] = useState(false) // 加载活动详情
    const [autoActivityBoxStatus, setAutoActivityBoxStatus] = useState(false)

    type AutoRefsType = {
        // 子组件暴露给父组件的方法

        getData: any;
        // setAddpritVstatus1: () => void;
    };
    const autoRefs = useRef<AutoRefsType>(null);

    const getColumns = [{
        title: '活动名称',
        // dataIndex: 'title',
        key: 'title',
        render: (text: any, record: any) => {
            return <Space direction="vertical" size={2}>
                <div className="tit">
                    {record.title}
                </div>
                <Tag bordered color={
                    (record.business_code === 'LimitTime' || record.business_code === '') ? '#6C26FD' : record.business_code === 'LimitQuantity' ? '#2B71FF' : '#252931'
                } transparentBg>{(record.business_code === 'LimitTime' || record.business_code === '') ? '限时抢购' : record.business_code === 'LimitQuantity' ? '限量抢购' : record.business_code === 'OrdinaryTimeBuy' ? '普通降价促销' : ''}</Tag>
            </Space>
        }
    }, {
        title: '预热开始时间',
        // dataIndex: 'campaign_status',
        key: 'campaign_status',
        render: (text: any, record: any) => {
            return record.pre_begin_time === record.begin_time ? '-' : record.pre_begin_time
        }
    }, {
        title: '活动时间',
        // dataIndex: 'product_id',
        key: 'time',
        render: (text: any, record: any) => {
            return <Space direction="vertical" size={2}>
                <div className="tit">{record.begin_time}</div>
                <div className="tit">{record.end_time}</div>
            </Space>
        }
    }, {
        title: '优惠类型',
        // dataIndex: 'start_time',
        key: 'shop_stype',
        render: (text: any, record: any) => {

            return <div>
                {record.shop_stype === '1' ? '一口价' : record.shop_stype === '2' ? '直降' : record.shop_stype === '3' ? '打折' : ''}
            </div>
        }
    }, {
        title: '活动状态',
        // dataIndex: 'start_time',
        key: 'campaign_status',
        render: (text: any, record: any) => {
            // record.campaign_status = record.campaign_status + ''
            return <Tag.Status type={record.campaign_status === '1' ? 'warn' : record.campaign_status === '2' ? 'success' : record.campaign_status === '3' ? 'cancel' : record.campaign_status === '4' ? 'cancel' : record.campaign_status === '6' ? 'default' : record.campaign_status === '7' ? 'error' : 'cancel'}>
                {record.campaign_status === '1' ? '未开始' : record.campaign_status === '2' ? '进行中' : record.campaign_status === '3' ? '已失效' : record.campaign_status === '4' ? '已结束' : record.campaign_status === '6' ? '处理中' : record.campaign_status === '7' ? '已删除' : ''}
            </Tag.Status>
        }
    }, {
        title: '操作',
        // dataIndex: 'start_time',
        key: 'campaign_status',
        render: (text: any, record: any) => {
            //    const outTimeTowMtie = 
            // return 123
            return <Space direction="vertical" size={2}>
                <Space>
                    {record.campaign_status === '1' || record.campaign_status === '2' ?
                        <Tooltip title={record.lotime ? '' : '已经过了可失效的时间，所以本次不可再失效。'}>
                            {/* disabled={!record.lotime} */}
                            <Button type="link" onClick={() => {
                                Modal.warning({
                                    title: '确定失效活动?',
                                    content: '失效活动将影响商品曝光，您确定失效活动吗？',
                                    okText: '失效',
                                    onOk: () => {
                                        setFlashStatusFun({ "activity_id": record.merchant_activity_id, "status": 2 }).then((res: any) => {
                                            if (res.code === 0) {

                                                message.success('活动失效成功')

                                                getList()
                                            }
                                        })
                                    }

                                })
                            }}>失效活动</Button>
                        </Tooltip> : ''}
                    {record.showDeleteStatus && <>
                        <Button type="link" onClick={() => {

                            Modal.confirm({
                                title: '删除活动?',
                                content: '确认删除活动后，将永久删除，无法恢复',
                                okText: '删除',
                                onOk: () => {
                                    // try {
                                    //     // 保存起来 以便恢复删除项
                                    //     const dlyDeletActList = localStorage.getItem('dlyDeletActList')
                                    //     const dlyDeletActListJson = JSON.parse(dlyDeletActList as string)
                                    //     if (!dlyDeletActListJson) {
                                    //         localStorage.setItem('dlyDeletActList', JSON.stringify([record.merchant_activity_id]))
                                    //     } else {
                                    //         dlyDeletActListJson.push(record.merchant_activity_id)
                                    //         localStorage.setItem('dlyDeletActList', JSON.stringify(dlyDeletActListJson))
                                    //     }
                                    // } catch (error) {
                                    //     localStorage.setItem('dlyDeletActList', JSON.stringify([record.merchant_activity_id]))
                                    // }
                                    setFlashStatusFun({ "activity_id": record.merchant_activity_id, "status": 3 }).then((res: any) => {
                                        if (res.code === 0) {
                                            //     "status": 4 可以恢复已经删除的活动 前提得知道活动ID
                                            message.success('该活动已删除')
                                            // getListFlashWithTimeLimitData.page = 1
                                            // getListFlashWithTimeLimitData.page_size = 10
                                            getList()
                                        }
                                    })
                                }
                            })
                        }}>删除</Button>

                        {false && <Button type="link" onClick={() => {
                            console.log('复活活动')
                            setShowCopyActModal(true)
                            setGetDataLodin(true)
                            getDetailFlashAndGoods({ activity_id: record.merchant_activity_id }).then((res: any) => {
                                console.log('复活活动', res)
                                if (res.code === 0) {
                                    setCopyActItemOne(res.data)
                                    // setShowCopyActModal(true)
                                    setGetDataLodin(false)
                                }
                            })
                            // setCopyActItemOne(record)
                        }}>复活活动</Button>}
                    </>}
                    <Button type="link" onClick={() => {
                        if (!cheackLoginfatyer()) return
                        console.log('活动自动续期')
                        setAutoActivityBoxStatus(true)
                        setGetDataLodin(true)
                        getDetailFlashAndGoods({ activity_id: record.merchant_activity_id }).then((res: any) => {
                            console.log('活动自动续期', res)
                            if (res.code === 0) {
                                setCopyActItemOne(res.data)
                                // setShowCopyActModal(true)
                                setGetDataLodin(false)
                            }
                        })
                        // setCopyActItemOne(record)
                    }}>活动自动续期</Button>
                </Space>
                {record.refoStatu !== 0 && <Space>
                    <div style={{
                        color: record.refoStatu === 1 ? '#1890FF' : record.refoStatu === 2 ? '#43C781' : '#FF4D4F',
                        width: 100,
                    }}>
                        <Tooltip.Auto title={record.msg} lineClamp={1}>
                            {record.msg}
                        </Tooltip.Auto>
                    </div>
                </Space>}
            </Space>
        }
    }]
    const addnewPrd: any = useAppSelector((state) => state.autoCounps.addnewPrd)
    const isBuyStatus = useAppSelector(
        (state) => state.jinritemaiProduct.isBuyStatus
    )
    function cheackLoginfatyer(show = false) {
        // console.log('addnewPrd', addnewPrd)
        if (!addnewPrd) {
            if (!show) {
                Modal.warning({
                    title: "提示",
                    content: (
                        <>
                            插件版本过旧无法使用请前往官网
                            <Button
                                type="link"
                                onClick={(e) => {
                                    open("https://doulingyang.cn")
                                }}>
                                doulingyang.cn
                            </Button>
                            下载最新版本后刷新页面使用！！
                        </>
                    ),
                    okText: "知道了",
                    centered: false
                })
                return false
            }
            return false
        }
        // console.log('isBuyStatus.status', isBuyStatus)
        if (isBuyStatus.status) {
            if (!show) {
                Modal.confirm({
                    title: isBuyStatus.title,
                    content: isBuyStatus.content,
                    icon: null,
                    okText: isBuyStatus.okText,
                    cancelText: " 取消",
                    onOk: () => {
                        open(isBuyStatus.url)
                        return
                    }
                })
                return false
            }

            return false
        }
        // console.log('cheackLogin()', cheackLogin())
        // if (cheackLogin()) {
        //     if (!show) {
        //         Modal.warning({
        //             title: "提示",
        //             content: "请先登录后使用插件",
        //             okText: "前往登录",
        //             onOk: () => {
        //                 setShowLoginBox(true)
        //             }
        //             // centered: false,
        //         })
        //         return false
        //     }
        //     return false
        // }
        return true
    }

    function setFlashStatusFun(data) {
        return new Promise((resolve, reject) => {
            setGetListLodin(true)
            setFlashStatus(data).then((res: any) => {
                setGetListLodin(false)
                resolve(res)
            })
        })
    }
    function getList() {
        setGetListLodin(true)
        // setLodinDataStatus(true)
        getListFlashWithTimeLimit(getListFlashWithTimeLimitData).then((res: any) => {
            console.log('resAsd', res)
            setGetListLodin(false)
            // setLodinDataStatus(false)

            setTotals(res.total)
            let lotime = 2 * 60 * 60 * 1000
            res.data && res.data.flash_list.forEach((itemconter) => {
                let nowTime = new Date().getTime()
                let startTime = new Date(itemconter.begin_time).getTime()
                // let endTime = new Date(itemconter.end_time).getTime()
                // 判断活动是否已经开始两个小时 并且是开始 或者未开始的状态
                itemconter.refoStatu = 0 // 未开始动作 1 进行中 2成功 3失败
                itemconter.msg = '未开始'
                if (nowTime - startTime < lotime) {
                    itemconter.lotime = true
                } else {
                    itemconter.lotime = false
                }
                itemconter.campaign_status = itemconter.campaign_status + ''
                itemconter.shop_stype = itemconter.shop_stype + ''
                if (itemconter.campaign_status === '1' || itemconter.campaign_status === '2' || itemconter.campaign_status === '6' || itemconter.campaign_status === '7') {
                    itemconter.showDeleteStatus = false
                } else {
                    itemconter.showDeleteStatus = true
                }
            })
            setGetDataList(res.data ? res.data.flash_list : [])
        })
    }
    function setFlashStatusFunAll(data, isc) {
        if (!data || !data.length) {
            return message.warning('请选择活动')
        }
        let statusText = isc == 2 ? '失效' : '删除'

        const refoDataAll = data.map((item, index) => {
            const getIsItem = getDataList.find((itemdata) => {
                return itemdata.merchant_activity_id === item
            })
            getIsItem.refoStatu = 1
            getIsItem.msg = '进行中'
            return setFlashStatus({
                "activity_id": item,
                "status": isc
            }).then((res: any) => {
                if (!res.code) {


                    getIsItem.refoStatu = 2
                    getIsItem.msg = `${statusText}：成功`
                    getIsItem.showDeleteStatus = true
                    setGetDataList([...getDataList])
                    if (isc === 2) {
                        getIsItem.campaign_status = '3'
                        selectGoodsKeys.splice(selectGoodsKeys.indexOf(item), 1)
                    } else {
                        getIsItem.campaign_status = '7'
                        getIsItem.showDeleteStatus = false
                        selectkeysDelet.splice(selectkeysDelet.indexOf(item), 1)
                    }
                } else {
                    getIsItem.refoStatu = 3
                    getIsItem.msg = `${statusText}失败:${res.msg}`
                    setGetDataList([...getDataList])
                }
                return Promise.resolve(res)
            })
        })
        setGetDataList([...getDataList])
        setGetListLodin(true)
        Promise.all(refoDataAll).then((res) => {
            if (isc === 2) {
                setSelectGoodsKeys([...selectGoodsKeys])
            } else {
                setSelectkeysDelet([...selectkeysDelet])
            }
            // console.log('res', res)
            // message.success(`已全部${statusText}`)
            let scsessLen = 0
            let errorLen = 0
            res.forEach((item) => {
                if (!item.code) {
                    scsessLen++
                } else {
                    errorLen++
                }
            })
            Modal.confirm({
                title: '提示',
                content: (() => {
                    if (scsessLen === res.length) {
                        return <div>
                            <p>{scsessLen}个活动 已全部{statusText}</p>
                        </div>
                    }
                    if (errorLen === res.length) {
                        return <div>
                            <p>{errorLen}个活动 {statusText}失败， 请检查列表</p>
                        </div>
                    }
                    return <div>
                        <p>{scsessLen}个活动 已全部{statusText}</p>
                        <p>{errorLen}个活动 {statusText}失败， 请检查列表</p>
                    </div>
                })(),
                okText: '知道了',
                showCancel: false
            })

            setGetListLodin(false)
        })
    }
    return (<div>
        <Form
            size="small"
            name="getLtalpSerch"
            layout='inline'
        >
            <Form.Item label="活动名称" style={{
                marginBottom: 10
            }}>
                <Input placeholder="请输入活动名称" disabled={getListLodin} value={getListFlashWithTimeLimitData.title} size="small" allowClear onChange={(e) => {
                    getListFlashWithTimeLimitData.title = e.target.value
                    setGetListFlashWithTimeLimitData({ ...getListFlashWithTimeLimitData })
                }} />
            </Form.Item>
            <Form.Item label="商品ID" style={{
                marginBottom: 10
            }}>
                <Input placeholder="请输入商品ID" disabled={getListLodin} value={getListFlashWithTimeLimitData.product_id} size="small" allowClear onChange={(e) => {
                    getListFlashWithTimeLimitData.product_id = e.target.value
                    setGetListFlashWithTimeLimitData({ ...getListFlashWithTimeLimitData })

                }} />
            </Form.Item>
            <Form.Item label="活动状态" style={{
                marginBottom: 10
            }}>
                <Select style={{ width: 200 }} disabled={getListLodin} value={getListFlashWithTimeLimitData.campaign_status} size="small" onChange={(e: any) => {
                    getListFlashWithTimeLimitData.campaign_status = e
                    setGetListFlashWithTimeLimitData({ ...getListFlashWithTimeLimitData })
                }}>
                    <Option value="">全部</Option>
                    <Option value="1">未开始</Option>
                    <Option value="2">进行中</Option>
                    <Option value="6">处理中</Option>
                    <Option value="4">已结束</Option>
                    <Option value="3">已失效</Option>

                </Select>
            </Form.Item>
            <Form.Item label="优惠类型" style={{
                marginBottom: 10
            }}>
                <Select value={getListFlashWithTimeLimitData.shop_stype} disabled={getListLodin} style={{ width: 200 }} size="small" onChange={(e: any) => {
                    getListFlashWithTimeLimitData.shop_stype = e
                    setGetListFlashWithTimeLimitData({ ...getListFlashWithTimeLimitData })
                }}>

                    <Option value="">全部</Option>
                    <Option value="1">一口价</Option>
                    <Option value="2">直降</Option>
                    <Option value="3">打折</Option>
                </Select>
            </Form.Item>
            <Form.Item label="活动类型" style={{
                marginBottom: 10
            }}>
                <Select value={getListFlashWithTimeLimitData.business_code} disabled={getListLodin} style={{ width: 200 }} size="small" onChange={(e: any) => {
                    getListFlashWithTimeLimitData.business_code = e
                    setGetListFlashWithTimeLimitData({ ...getListFlashWithTimeLimitData })
                }}>
                    <Option value="">全部</Option>
                    <Option value="LimitTime">限时抢购</Option>
                    <Option value="LimitQuantity">限量抢购</Option>
                    <Option value="OrdinaryTimeBuy">普通降价促销</Option>
                </Select>
            </Form.Item>
            <Space>

                <Button type="primary" size="mini" disabled={getListLodin} loading={getListLodin} onClick={() => {
                    getListFlashWithTimeLimitData.page = 1
                    setGetListFlashWithTimeLimitData({ ...getListFlashWithTimeLimitData })
                    getList()
                }}>查询</Button>
                <Button size="mini" disabled={getListLodin} onClick={() => {
                    console.log('重置')
                    setGetListFlashWithTimeLimitData({ ...dataInfo })
                    // setCouponTime(null)
                    // setCouDataInfo({ ...dataInfo })
                }}>重置</Button>

            </Space>
        </Form>
        <div className="getData" style={{
            margin: '10px 0 20px'
        }}>
            <Space>
                <div>选择批量操作类型：</div>
                <Radio.Group
                    // options={
                    //     [{ label: '失效活动', value: '0' },
                    //     { label: '复活活动', value: '1' },
                    //     { label: '删除活动', value: '2' }]
                    // }
                    // defaultValue={'Pear'}
                    // optionType="button"
                    // buttonStyle="solid"
                    size="small"
                    onChange={(e: any) => {
                        // console.log('e', e.target.value)
                        setSelectActType(e.target.value)
                    }}
                    value={selectActType}
                    disabled={getListLodin}
                >
                    <Radio.Button value="0">失效活动</Radio.Button>
                    {/* <Radio.Button value="1">复活活动</Radio.Button> */}
                    <Radio.Button value="2">删除活动</Radio.Button>
                </Radio.Group>
                <Button type="primary" disabled={getListLodin} size="mini" onClick={() => {
                    if (selectActType === '0') {
                        setFlashStatusFunAll(selectGoodsKeys, 2)
                    }
                    if (selectActType === '2') {
                        setFlashStatusFunAll(selectkeysDelet, 3)
                    }
                }}>
                    {selectActType === '0' ? '批量失效' : selectActType === '1' ? '批量复活' : '批量删除'}
                </Button>
            </Space>

        </div>
        <Table
            columns={getColumns}
            dataSource={getDataList}
            rowKey='merchant_activity_id'
            loading={getListLodin}
            scroll={{
                y: 700
            }}
            rowSelection={{
                type: 'checkbox',
                selectedRowKeys: ((() => {

                    if (selectActType === '0') {
                        return selectGoodsKeys
                    } else {
                        return selectkeysDelet
                    }
                    // return selectGoodsKeys
                })()),
                onChange: (selectedRowKeys: any, selectedRows: any) => {
                    if (selectActType === '0') {
                        setSelectGoodsKeys(selectedRowKeys)
                    } else {
                        setSelectkeysDelet(selectedRowKeys)
                    }

                    console.log('selectedRows', selectedRows)
                    // setSelectGoodsList(selectedRows)
                },
                getCheckboxProps: (record) => {
                    if (selectActType === '0') {
                        //&& record.lotime
                        if (record.campaign_status === '1' || record.campaign_status === '2') {
                            return {
                                disabled: false
                            }
                        }
                        return {
                            disabled: true
                        }
                    }
                    if ((selectActType === '1' || selectActType === '2') && record.showDeleteStatus) {
                        return {
                            disabled: false
                        }
                    }
                    return {
                        disabled: true
                    }
                },
            }}

            pagination={{
                hideOnSinglePage: true,
                current: getListFlashWithTimeLimitData.page,
                pageSize: getListFlashWithTimeLimitData.pageSize,
                total: total,
                // pageSizeOptions: []
                showSizeChanger: true,
                showQuickJumper: true,
                onChange: (page: number, pageSize: number) => {
                    getListFlashWithTimeLimitData.page = page
                    getListFlashWithTimeLimitData.pageSize = pageSize
                    setGetListFlashWithTimeLimitData({ ...getListFlashWithTimeLimitData })
                    getList()
                },
                showTotal: (total, range) => {
                    return `共 ${total} 条数据`
                }
            }}
        >
        </Table>

        <Modal
            title="复活活动"
            visible={showCopyActModal}
            onCancel={() => setShowCopyActModal(false)}
            onOk={() => {
                setShowCopyActModal(false)
            }}
        ><Spin spinning={getDataLodin}>
                <CopyAct copyData={copyActItemOne}></CopyAct>
            </Spin>
        </Modal>

        <Modal
            title="添加活动自动续期"
            visible={autoActivityBoxStatus}
            onCancel={() => setAutoActivityBoxStatus(false)}
            onOk={() => {
                if (autoRefs.current) {
                    const { addLtaLpConfig, autoSetConfig } = autoRefs.current?.getData
                    // console.log('getDatas', getDatas)
                    // addLtaLpConfig.promotion_goods = addLtaLpConfig.promotion_goods.map((setUseNum) => {
                    //     setUseNum.useNumber = 0
                    //     return setUseNum
                    // })
                    // console.log('addLtaLpConfig', addLtaLpConfig)

                    window.postMessage({
                        type: 'dly_activity_modole',
                        dly_method: 'add',
                        shop_id: store.getState().jinritemaiShops.userShopId,
                        data: {
                            addLtaLpConfig,
                            autoSetConfig,
                            id: createTaskId(),
                            create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
                            updata_time: moment().format('YYYY-MM-DD HH:mm:ss'),
                        }
                    })
                }
                setAutoActivityBoxStatus(false)
            }}
            destroyOnClose={true}
        ><Spin spinning={getDataLodin}>
                <AutoSetActBox copyData={copyActItemOne} ref={autoRefs} />
            </Spin>
        </Modal>
    </div>)
}

export default forwardRef(SetLtaLp)